import os
import random

from PIL import Image, ImageDraw, ImageFilter, ImageFont


def get_random_color(): # 生成随机颜色
    
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)

    color = (r, g, b)
    return color

def generate_imagecode(): # 生成图片
    size = (130, 50)
    img = Image.new('RGB', size, color=get_random_color()) # 创建画布
    font = ImageFont.truetype('C:/Windows/Fonts/simhei.ttf', 40) # 创建字体
    # 创建imagedraw对象
    draw = ImageDraw.Draw(img)
    
    s = '1yytrfekjkfd1fewhfwehWWARTGDGHHDDDVJHWDWdjawdjaWDDD233329889398'
    code = ''
    for i in range(4):
        c = random.choice(s)
        code += c
        draw.text((5 + random.randint(4,7) + i * 30+10, 10), text=c, 
                  fill=get_random_color(), font=font)
        
    # 绘制验证码中的干扰线
    for i in range(6):
        x1 = random.randint(0, size[0]) 
        y1 = random.randint(0, size[1]/2)
              
        x2 = random.randint(0, size[0])        
        y2 = random.randint(size[1]/2, size[1])
        draw.line(((x1, y1), (x2, y2)), fill=get_random_color())
    
    # 添加滤镜
    img = img.filter(ImageFilter.BoxBlur(1.5))
    
    # print(f'code: {code}') 
    # code_dir = Config.CAPTCHA_DIR
    # if os.path.exists(code_dir) is False:
    #     os.mkdir(code_dir)
    # img.save(os.path.join(code_dir, f'{code}.png')) # 保存图片
    
    return img, code
    

if __name__ == '__main__':
    generate_imagecode()